package com.tianji.learning.mq;


import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.ObjectUtils;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.service.IInteractionReplyService;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Exchange.ORDER_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.*;
import static com.tianji.common.constants.MqConstants.Queue.QA_LIKE_TIMES_QUEUE;

@Slf4j
@Component
@RequiredArgsConstructor
public class LikeTimesChangeListener {
    private final IInteractionReplyService replyService;

    /**
     * 01 监听点赞数量消息 -> 修改问题回复表点赞数量 （day06-随堂-03）
     *
     * @param likedTimesMsg
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = QA_LIKE_TIMES_QUEUE, durable = "true"),
            exchange = @Exchange(name = LIKE_RECORD_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = QA_LIKED_TIMES_KEY
    ))
    public void listenLikeTimesChangeMsg(List<LikedTimesDTO> likedTimesMsg) {
        //1 健壮性处理
        if (ObjectUtils.isEmpty(likedTimesMsg)) {
            //数据有问题，无需要处理
            log.error("点赞数量有误，无法更新到问题回复表中");
            return;
        }
        //2 根据ID更新回复对应的点赞数
        log.info("监听到点赞消息变更数据 ：{}", likedTimesMsg);
        List<InteractionReply> replyList =new ArrayList<>(likedTimesMsg.size());
        for (LikedTimesDTO likedTimesDTO : likedTimesMsg) {
            InteractionReply reply = new InteractionReply()
                    .setLikedTimes(likedTimesDTO.getLikedTimes())
                    .setId(likedTimesDTO.getBizId());
            replyList.add(reply);
        }
        replyService.updateBatchById(replyList, 100);
    }


}
